package com.syjy.tunnelworker.gathers.iml;

import com.syjy.DataExchangeException;
import com.syjy.PointDataCalculator;
import com.syjy.container.ProtocolDataContainer;
import com.syjy.tunnelinfo.DataPoint;
import com.syjy.tunnelinfo.TunnelStatus;
import com.syjy.tunnelinfo.gathertunnelinfo.CalculatorTunnelInfo;
import com.syjy.tunnelworker.BaseProtocolTunnel;
import com.syjy.tunnelworker.gathers.DataGatherInterface;
import org.apache.commons.lang.StringUtils;
import wei.yigulu.netty.BaseProtocolBuilder;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * 点位计算器采集通道
 *
 * @author: xiuwei
 * @version:
 */
public class CalculateDataGather extends BaseProtocolTunnel<CalculatorTunnelInfo, BaseProtocolBuilder> implements DataGatherInterface {


	/**
	 * 计算器池
	 */
	Map<Integer, PointDataCalculator> calculatorMap;


	/**
	 * 顶层的构造方法
	 *
	 * @param tunnelInfo 通道信息
	 */
	public CalculateDataGather(CalculatorTunnelInfo tunnelInfo) {
		super(tunnelInfo);
	}

	@Override
	public BaseProtocolTunnel startTunnel() throws DataExchangeException {
		protocolTunnelContainer.addUpdateDateTask(this);
		setTunnelStatus(TunnelStatus.CONNECTED);
		return this;
	}

	@Override
	public BaseProtocolTunnel buildTunnel() throws DataExchangeException {
		parseGatherDataPoint();
		return this;
	}

	@Override
	public void parseGatherDataPoint() throws DataExchangeException {
		calculatorMap = new HashMap<>();
		for (DataPoint d : this.tunnelInfo.getDataPoints()) {
			if (StringUtils.isNotEmpty(d.getFormula())) {
				calculatorMap.put(d.getId(),new PointDataCalculator(d));
			}
		}
	}

	@Override
	public void getDataFromProtocol() throws DataExchangeException {
		ProtocolDataContainer protocolDataContainer=ProtocolDataContainer.getInstance();
			for(Integer i  : this.calculatorMap.keySet()){
				if(this.calculatorMap.get(i).getDataTypeFlag()==1){
					protocolDataContainer.putNumber(i,new BigDecimal(this.calculatorMap.get(i).calculate().toString()));
				}else{
					protocolDataContainer.putBoolean(i,(Boolean) (this.calculatorMap.get(i).calculate()));
				}
			}
	}
}
